from urllib import request,parse
import json

def fanyi(keyword):
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    data = {'i':keyword}
    data['doctype']='json'

    data = parse.urlencode(data)
    headers = {'Content-Length':len(data)}

    #创建请教，发送请求，爬取信息
    req = request.Request(url,data=bytes(data,encoding='utf-8'),headers=headers)
    res = request.urlopen(req)

    #解析结果
    str_json = res.read().decode('utf-8')
    #print(str_json)
    myjson = json.loads(str_json)
    #print(myjson)
    print(myjson['translateResult'][0][0]['tgt'])

if __name__ == '__main__':
    while True:
        keyword = input('请输入要翻译的文字：')
        if keyword =='q':
            break
        else:
            fanyi(keyword)
